<template>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="auto">
        <el-row type="flex" :gutter="10">
            <el-col :span="12">
                <el-form-item label="优惠券名称" prop="coupon_name">
                    <el-input v-model="formData.coupon_name" clearable placeholder="请输入"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="类型" prop="coupon_type">
                    <el-select v-model="formData.coupon_type" placeholder="请选择">
                        <el-option label="满减券" :value="1"></el-option>
                        <el-option label="折扣券 " :value="2"></el-option>
                        <el-option label="现金券" :value="3"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
			<!-- use_type 使用范围 1全平台 2商城 3外卖 4商户 -->
            <el-col :span="24">
                <el-form-item label="使用范围" prop="use_type">
                    <el-radio-group v-model="formData.use_type" placeholder="请选择" @change="formData.merch_ids = []">
                        <el-radio :label="1" value="1">全平台</el-radio>
                        <el-radio :label="2 " value="2">商城</el-radio>
                        <!-- <el-radio :label="3" value="3">外卖</el-radio> -->
						 <el-radio :label="4" value="4">商户</el-radio>
						 <el-radio :label="5" value="5">停车场</el-radio>
						 <el-radio :label="6" value="6">指定商品</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="12" v-if="formData.use_type == 2||formData.use_type == 4||formData.use_type == 6">
                <el-form-item label="可用供应商" prop="merch_ids" v-if="formData.use_type == 2">
                    <el-link @click="openChooseStore" type="primary">
                        {{ formData.merch_ids?.length ? `已选择${formData.merch_ids.length}个供应商` : '选择供应商' }}
                    </el-link>
                    <chooseStore v-model="formData.merch_ids" ref="chooseStore" :title="'选择供应商'"></chooseStore>
                </el-form-item>
                <el-form-item label="可用商户" prop="merch_ids" v-if="formData.use_type == 4">
                    <el-link @click="openChoosemerchart" type="primary">
                        {{ formData.merch_ids?.length ? `已选择${formData.merch_ids.length}个商户` : '选择商户' }}
                    </el-link>
                    <choosemerchart  @confirm="getlistdata" v-model="formData.merch_ids" ref="choosemerchart" :title="'选择商户'"></choosemerchart>
					<div style="display: flex;flex-wrap: wrap;">
						<p v-for="(item,index) in formData.store_desc" :key="index" style="margin-right: 5px;">
							{{item}}、
						</p>
					</div>
                </el-form-item>
				<el-form-item label="可用商品" prop="goods_id" v-if="formData.use_type == 6">
				    <el-link @click="opengoodschoose" type="primary">
				        {{ formData.goods_id?.length ? `已选择${formData.goods_id.length}个商品` : '选择商品' }}
				    </el-link>
				    <goodschoose  v-model="formData.goods_id" ref="goodschoose" :title="'选择商品'"></goodschoose>
				</el-form-item>
            </el-col>
            <el-col :span="12" v-if="formData.coupon_type == 1||formData.coupon_type == 3">
                <el-form-item label="优惠金额" prop="coupon_money" :rules="[
                    {
                        required: true,
                        message: '必填项不能为空'
                    },
                    {
                        pattern: /^\d{0,4}(\.\d{0,2})?$/,
                        message: '金额格式错误'
                    }
                ]">
                    <el-input v-model="formData.coupon_money" clearable placeholder="请输入"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12" v-if="formData.coupon_type == 2">
                <el-form-item label="折扣比例" prop="discount_percent" :rules="[
                    {
                        required: true,
                        message: '必填项不能为空'
                    },
                    {
                        pattern: /^[1-9][0-9]*/,
                        message: '请输入正整数'
                    }
                ]">
                    <el-input v-model="formData.discount_percent" clearable placeholder="数字例如：86为八六折"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="消费门槛" prop="usable_money">
                    <el-input v-model="formData.usable_money" clearable placeholder="例如满300可使用填写300"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="发放数量" prop="coupon_num">
                    <el-input v-model="formData.coupon_num" clearable placeholder="请输入"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="领券开始时间" prop="start_time">
                    <!-- <el-date-picker type="datetime" placeholder="请选择"  value-format="yyyy-MM-dd HH:mm"
                        v-model="formData.start_time"></el-date-picker> -->
						<el-date-picker type="datetime" v-model="formData.start_time"  value-format="yyyy-MM-dd HH:mm"
						    placeholder="请选择">
						</el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="领券结束时间" prop="end_time">
					<!-- <el-date-picker type="datetime" v-model="formData.end_time"  value-format="yyyy-MM-dd HH:mm"
					    placeholder="请选择">
					</el-date-picker> -->
					<el-date-picker type="datetime" v-model="formData.end_time"  value-format="yyyy-MM-dd HH:mm"
					    placeholder="请选择">
					</el-date-picker>
                </el-form-item>
            </el-col>
            <!-- 过期方式 1固定时间区间 2领取后多少天内过期 单选 -->
            <el-col :span="12">
                <el-form-item label="过期方式" prop="expire_type">
                    <el-radio-group v-model="formData.expire_type" placeholder="请选择">
                        <el-radio :label="1" value="1">固定时间区间</el-radio>
                        <el-radio :label="2" value="2">领取后多少天内过期</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
            <!-- 过期时间 日期选择 -->
            <el-col :span="12" v-if="formData.expire_type == 1">
                <el-form-item label="过期时间" prop="use_time">
                    <el-date-picker type="datetime" v-model="formData.use_time"  value-format="yyyy-MM-dd HH:mm"
                        placeholder="请选择">
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <!-- 过期天数 -->
            <el-col :span="12" v-if="formData.expire_type == 2">
                <el-form-item label="过期天数(天)" prop="use_day">
                    <el-input-number v-model="formData.use_day" :min="1" :precision="0" :step="1" clearable placeholder="请输入过期天数"></el-input-number>
                </el-form-item>
            </el-col>
			<el-col :span="12">
				<el-form-item label="平台分摊比例" prop="rate">
					<div style="dispaly:flex">
						<el-input-number v-model="formData.rate" :precision="2" :max="1" :min="0" placeholder="2位小数，1为平台全额分摊"></el-input-number>
						<div>保留2位小数，1为平台全额分摊</div>
					</div>
				   
				</el-form-item>
			</el-col>

            <!-- <el-col :span="24">
                <el-form-item label="用户可领个数" prop="coupons_per_user">
                    <el-input-number v-model="formData.coupons_per_user" :min="0" :precision="0"></el-input-number>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="单天发放上限个数" prop="coupons_by_day">
                    <el-input-number v-model="formData.coupons_by_day" :min="0" :precision="0"></el-input-number>
                </el-form-item>
            </el-col> -->
            <el-col :span="12">
                <el-form-item label="上架状态" prop="status">
                    <el-switch v-model="formData.status" :active-value="1" :inactive-value="0"></el-switch>
                </el-form-item>
            </el-col>
			<!-- 是否赠送字段 is_send 0否 1是 -->
			<el-col :span="12">
				<el-form-item label="是否赠送" prop="is_send">
				    <el-switch v-model="formData.is_send" :active-value="1" :inactive-value="0"></el-switch>
				</el-form-item>
			</el-col>
            <el-col :span="24">
                <el-form-item label="使用须知" prop="ship_note">
                    <el-input type="textarea" v-model="formData.ship_note" clearable placeholder="请输入"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row type="flex" justify="center">
            <el-button type="primary" icon="el-icon-check" @click="confirm">
                <span>编辑优惠券</span>
                <span>{{ index }}/{{ editList.length }}</span>
            </el-button>
            <el-button type="default" icon="el-icon-close" @click="cancel">取消</el-button>
        </el-row>
    </el-form>
</template>

<script>
import { post } from "@/assets/js/http.js";
import chooseStore from "@/components/choose-store.vue";
import choosemerchart from '../../components/choose-merchart.vue'
import goodschoose from '../../components/goodschoose.vue'
import moment from 'moment';
export default {
    props:{
        show:Boolean,
        selection:Array
    },  
    components: { chooseStore,choosemerchart,goodschoose },
    name: "add-coupon",
    data() {
		var checkAge = (rule, value, callback) => {
			console.log(value,'value')
		        if (value=='') {
					value=0
		          // return callback(new Error('平台分摊比例不能为空'));
		        }
		        setTimeout(() => {
		          if (0>value||value> 1) {
		            callback(new Error('必须低于1'));
					// value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')
					// value=value.replace(/[^0-9.]/g,'').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')
					// console.log(value,'value',value.toFixed(2))
					// if()
		          } else {
		            callback();
		          }
		        }, 1000);
		      };
        return {
            index:1,
            editList:[],
            formData: {
                coupon_name: "",
                coupon_type: "",//类型 1满减券 2折扣券 3现金券
                coupon_money: "",
                use_type: "",//使用类型 1全平台 2商城 3外卖
                discount_percent: "",
                usable_money: "",
                coupon_num: "",
                start_time: "",
                end_time: "",
                expire_type: "1",//过期方式 1固定时间区间 2领取后多少天内过期
                use_time: "", //过期时间expire_type=1必传 日期格式 2023-10-15
                use_day: "",//过期天数 expire_type=2必传
                merch_ids: [],//商家/供应商Id 适用的商户、供应商的id，多个逗号连接 use_type=2时选择供应商id，use_type=3是选择商家id，不传为所有商家通用
                coupons_per_user: 1,
                coupons_by_day: 1,
                status: "1",
				is_send:'',
                ship_note: "",
				goods_id:[],
				rate:'',
				store_desc:[],
            },
            formRules: {
                coupon_name: {
                    required: true,
                    message: "必填项不能为空"
                },
                coupon_type: {
                    required: true,
                    message: "必填项不能为空"
                },
                usable_money: [
                    {
                        required: true,
                        message: "必填项不能为空"
                    },
                    {
                        pattern: /^\d{0,4}(\.\d{0,2})?$/,
                        message: "金额格式错误"
                    }
                ],
                expire_type: [
                    {
                        required: true,
                        message: "必填项不能为空"
                    }
                ],
                use_day: [
                    {
                        required: true,
                        message: "必填项不能为空"
                    }
                ],
                use_time: [
                    {
                        required: true,
                        message: "必填项不能为空"
                    }
                ],
				rate: [{ validator: checkAge, trigger: 'blur' }],
				

                coupon_num: [
                    {
                        required: true,
                        message: "必填项不能为空"
                    },
                    {
                        pattern: /^[1-9][0-9]*/,
                        message: "请输入正整数"
                    }
                ],
                use_type: [
                    {
                        required: true,
                        message: "必填项不能为空"
                    }
                ],
                start_time: {
                    required: true,
                    message: "必填项不能为空"
                },
                end_time: {
                    required: true,
                    message: "必填项不能为空"
                },
                coupons_per_user: {
                    required: true,
                    message: "必填项不能为空"
                },
                coupons_by_day: {
                    required: true,
                    message: "必填项不能为空"
                },
                status: {
                    required: true,
                    message: "必填项不能为空"
                },
				is_send: {
                    required: true,
                    message: "必填项不能为空"
                },
                ship_note: {
                    required: true,
                    message: "必填项不能为空"
                }
            }
        };
    },
    watch:{
        show:{
            deep:true,
            immediate:true,
            handler(){
                if(this.show){
                    this.resetEdit()
                }
            },
        }
    },
    methods: {
        resetEdit(){
            this.index = 1
            this.editList = JSON.parse(JSON.stringify(this.selection))
            this.formData = this.$options.data().formData
            this.formatIndexEdit()
        },
        formatIndexEdit(){ 
            this.formData = this.editList[this.index-1]
			console.log(this.formData,'formData',this.selection[0])
            this.formData.end_time && (this.formData.end_time = moment(this.formData.end_time*1000).format('yyyy-MM-DD HH:mm'))
            this.formData.start_time && (this.formData.start_time = moment(this.formData.start_time*1000).format('yyyy-MM-DD HH:mm'))
            this.formData.merch_ids && (this.formData.merch_ids = this.formData.merch_ids.split(","))
			this.formData.store_desc && (this.formData.store_desc = this.formData.store_desc.split(","))
			this.formData.goods_id && (this.formData.goods_id = this.formData.goods_id.split(","))
			},
        confirm() {
			console.log(this.formData.coupon_money,this.formData.usable_money,+this.formData.coupon_money>=(+this.formData.usable_money))
            this.$refs.formRef.validate(async isValid => {
                if (isValid) {
					if(this.formData.coupon_type==1||this.formData.coupon_type == 3){
						// if((+this.formData.coupon_money>(+this.formData.usable_money))==true){
						// 	this.$message('优惠金额要小于消费门槛')
						// 	return
						// }
					}
                    const formData = JSON.parse(JSON.stringify(this.formData));
                    formData.start_time =
                        new Date(formData.start_time).getTime() / 1000;
                    formData.end_time =
                        new Date(formData.end_time).getTime() / 1000;
						formData.merch_ids?.length && (formData.merch_ids = formData.merch_ids.join(","));
						formData.goods_id?.length && (formData.goods_id = formData.goods_id.join(","));
						

                   
                    await post({
                        url: "/admin/shop.coupon/edit",
                        data: formData,
                        loading: true,
                        successTip: true
                    });
                    this.$emit("update");
                    if(this.index == this.editList.length){
                        this.$parent.$emit("update:visible", false);
                        this.$refs.formRef.resetFields();
                        return
                    }else{
                        this.index++
                        this.formatIndexEdit()
                    }
                }
            });
        },
        cancel() {
            this.$parent.$emit("update:visible", false);
            this.$refs.formRef.resetFields();
        },
        openChooseStore() {
            this.$refs.chooseStore.open();
        },
		openChoosemerchart(){
			this.$refs.choosemerchart.open();
		},
		opengoodschoose(){
			this.$refs.goodschoose.open();
		},
		getlistdata(result){
			this.formData.store_desc = []
			console.log(result,'result')
			result.forEach(item=>{
				this.formData.store_desc.push(item.merch_name)
			})
		}
    }
};
</script>